package com.jnu.myaccount_drawer.ui.history;

import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jnu.myaccount_drawer.InputActivity;
import com.jnu.myaccount_drawer.R;
import com.jnu.myaccount_drawer.data.AccountType;
import com.jnu.myaccount_drawer.data.DataBank;
import com.jnu.myaccount_drawer.ui.manage.DetailActivity;

import java.util.List;

public class HistoryFragment extends Fragment {
    private DataBank dataBankHistory;
    private List<AccountType> accountTypeHistory;
    private HistoryFragment.MyRecyclerViewAdapterHistory recyclerViewAdapterHistory;
    private DataBank dataBankRenew;
    private TextView textViewIncomePrice;
    private TextView textViewOutcomePrice;
    private TextView textViewNetAssetsPricePrice;
    private double grossIncomeAll=0;
    private double grossOutcomeAll=0;

    public static final int RESULT_CODE_ADD_DATA = 996;

    ActivityResultLauncher<Intent> launcherDetail = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {

    });

    ActivityResultLauncher<Intent> launcherAdd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA){
                if(null==data)return;
                String type=data.getStringExtra("type");
                int pictureId=data.getIntExtra("pictureId",0);
                double price=data.getDoubleExtra("price",0);
                String payOrIncome=data.getStringExtra("payOrIncome");
                String payType=data.getStringExtra("payType");
                String date = data.getStringExtra("date");
                int position=data.getIntExtra("position",accountTypeHistory.size());
                if(pictureId==0)
                {
                    pictureId=R.drawable.other;
                }
                if(payOrIncome.equals("收入")) {
                    if(price>=0){
                        price=Math.abs(price);
                    }
                    else{
                        payOrIncome="支出";
                        price=-Math.abs(price);
                    }
                }
                else{//支出
                    if(price>=0){
                        price=-Math.abs(price);
                    }
                    else{
                        payOrIncome="收入";
                        price=Math.abs(price);
                    }
                }
                accountTypeHistory.add(position,new AccountType(type,pictureId,price,payType,payOrIncome,date));
                dataBankHistory.saveData();
                updateStatistics();
                recyclerViewAdapterHistory.notifyItemInserted(position);

            }
        }
    });

    ActivityResultLauncher<Intent> launcherEdit = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA) {
                if(null==data)return;
                String type = data.getStringExtra("type");
                int pictureId=data.getIntExtra("pictureId",0);
                double price = data.getDoubleExtra("price", 0);
                String payOrIncome=data.getStringExtra("payOrIncome");
                String payType=data.getStringExtra("payType");
                String date=data.getStringExtra("date");
                int position = data.getIntExtra("position", accountTypeHistory.size());
                if(pictureId==0) {
                    pictureId=R.drawable.other;
                }
                if(payOrIncome.equals("收入")) {
                    if(price>=0){
                        price=Math.abs(price);
                    }
                    else{
                        payOrIncome="支出";
                        price=-Math.abs(price);
                    }
                }
                else{//支出
                    if(price>=0){
                        price=-Math.abs(price);
                    }
                    else{
                        payOrIncome="收入";
                        price=Math.abs(price);
                    }
                }
                accountTypeHistory.get(position).setType(type);
                accountTypeHistory.get(position).setPrice(price);
                accountTypeHistory.get(position).setPictureId(pictureId);
                accountTypeHistory.get(position).setPayType(payType);
                accountTypeHistory.get(position).setPayOrIncome(payOrIncome);
                accountTypeHistory.get(position).setDate(date);
                dataBankHistory.saveData();
                updateStatistics();
                recyclerViewAdapterHistory.notifyItemChanged(position);
            }
        }
    });
    private List<AccountType> accountTypeHistoryRenew;

    public HistoryFragment() {
        // Required empty public constructor
    }

    public static HistoryFragment newInstance() {
        HistoryFragment fragment = new HistoryFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_history, container, false);
        initData();

        FloatingActionButton fabAdd=rootView.findViewById(R.id.floating_action_button_add);
        fabAdd.setOnClickListener(view -> {
            Intent intent=new Intent(this.getContext(), InputActivity.class);
            intent.putExtra("position",accountTypeHistory.size());
            launcherAdd.launch(intent);
        });

        //总收支 text_view_net_assets_price_history text_view_income_price_history
        TextView textViewIncomeAll = rootView.findViewById(R.id.text_view_income_price_history);
        TextView textViewOutcomeAll = rootView.findViewById(R.id.text_view_outcome_price_history);
        TextView textViewAccountAll = rootView.findViewById(R.id.text_view_net_assets_price_history);
        double grossIncomeAll=0;
        double grossOutcomeAll=0;
        for(int i =0; i <accountTypeHistory.size(); i++)
        {
            if(accountTypeHistory.get(i).getPrice()>=0)
            {
                grossIncomeAll+=accountTypeHistory.get(i).getPrice();//总收入
            }
            else
            {
                grossOutcomeAll-=accountTypeHistory.get(i).getPrice();//总支出
            }
        }
        double grossAccount = grossIncomeAll - grossOutcomeAll;
        textViewIncomeAll.setText(grossIncomeAll+"");
        textViewOutcomeAll.setText(grossOutcomeAll+"");
        textViewAccountAll.setText(grossAccount +"");

        RecyclerView mainRecyclerView=rootView.findViewById(R.id.recycler_view_items_history);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext());
        mainRecyclerView.setLayoutManager(layoutManager);

        recyclerViewAdapterHistory = new HistoryFragment.MyRecyclerViewAdapterHistory(accountTypeHistory);
        mainRecyclerView.setAdapter(recyclerViewAdapterHistory);
        return rootView;
    }

    private void initData() {
        dataBankHistory = new DataBank(this.getContext());
        accountTypeHistory= dataBankHistory.loadData();
    }

    private void renewData() {
        dataBankRenew = new DataBank(this.getContext());
        accountTypeHistoryRenew=dataBankRenew.loadData();//所有账目
    }

    private void updateStatistics() {
        textViewIncomePrice = getActivity().findViewById(R.id.text_view_income_price_history);
        textViewOutcomePrice = getActivity().findViewById(R.id.text_view_outcome_price_history);
        textViewNetAssetsPricePrice = getActivity().findViewById(R.id.text_view_net_assets_price_history);

        grossIncomeAll=0;
        grossOutcomeAll=0;

        renewData();

        for(int i =0; i <accountTypeHistoryRenew.size(); i++)
        {
            if(accountTypeHistoryRenew.get(i).getPrice()>=0)
            {
                grossIncomeAll+=accountTypeHistoryRenew.get(i).getPrice();//总收入
            }
            else
            {
                grossOutcomeAll-=accountTypeHistoryRenew.get(i).getPrice();//总支出
            }
        }
        double grossAccount = grossIncomeAll - grossOutcomeAll;
        textViewIncomePrice.setText(grossIncomeAll+"");
        textViewOutcomePrice.setText(grossOutcomeAll+"");
        textViewNetAssetsPricePrice.setText(grossAccount +"");
    }

    public class MyRecyclerViewAdapterHistory extends RecyclerView.Adapter {
        private final List<AccountType> accountTypeHistory;

        public MyRecyclerViewAdapterHistory(List<AccountType> accountTypeHistory) {
            this.accountTypeHistory=accountTypeHistory;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.account_holder_history, parent, false);

            return new HistoryFragment.MyRecyclerViewAdapterHistory.MyViewHolderHistory(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder Holder, int position) {
            HistoryFragment.MyRecyclerViewAdapterHistory.MyViewHolderHistory holderHistory = (HistoryFragment.MyRecyclerViewAdapterHistory.MyViewHolderHistory) Holder;
            holderHistory.getImageView().setImageResource(accountTypeHistory.get(position).getPictureId());
            holderHistory.getTextViewType().setText(accountTypeHistory.get(position).getType());
            holderHistory.getTextViewPrice().setText(accountTypeHistory.get(position).getPrice() +"");
            holderHistory.getTextViewDate().setText(accountTypeHistory.get(position).getDate());
            holderHistory.getTextViewPayType().setText(accountTypeHistory.get(position).getPayType());

            holderHistory.itemView.setOnClickListener(view -> {
                Intent intent=new Intent(HistoryFragment.this.getContext(), DetailActivity.class);
                intent.putExtra("position",holderHistory.getAdapterPosition());
                intent.putExtra("pictureId", accountTypeHistory.get(holderHistory.getAdapterPosition()).getPictureId());
                intent.putExtra("type", accountTypeHistory.get(holderHistory.getAdapterPosition()).getType());
                intent.putExtra("price", accountTypeHistory.get(holderHistory.getAdapterPosition()).getPrice());
                intent.putExtra("payOrIncome", accountTypeHistory.get(holderHistory.getAdapterPosition()).getPayOrIncome());
                intent.putExtra("payType", accountTypeHistory.get(holderHistory.getAdapterPosition()).getPayType());
                intent.putExtra("date", accountTypeHistory.get(holderHistory.getAdapterPosition()).getDate());
                launcherDetail.launch(intent);
            });
        }

        @Override
        public int getItemCount() {
            return accountTypeHistory.size();
        }

        private class MyViewHolderHistory extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
            private static final int CONTEXT_MENU_ID_EDIT = 1;
            private static final int CONTEXT_MENU_ID_DELETE = 2;

            private ImageView imageView;
            private TextView textViewType;
            private TextView textViewPrice;
            private TextView textViewPayType;
            private TextView textViewDate;

            public MyViewHolderHistory(View itemView) {
                super(itemView);

                this.imageView=itemView.findViewById(R.id.image_view_account);
                this.textViewType=itemView.findViewById(R.id.text_view_account_type);
                this.textViewPrice=itemView.findViewById(R.id.text_view_account_price);
                this.textViewPayType=itemView.findViewById(R.id.text_view_pay_type);
                this.textViewDate=itemView.findViewById(R.id.text_view_date_number);

                itemView.setOnCreateContextMenuListener(this);//创建菜单
            }

            public ImageView getImageView() { return imageView; }

            public TextView getTextViewType() { return textViewType; }

            public TextView getTextViewPrice() { return textViewPrice; }

            public TextView getTextViewPayType() { return textViewPayType; }

            public TextView getTextViewDate() { return textViewDate; }

            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                int position=getAdapterPosition();
                MenuItem menuItemEdit=contextMenu.add(Menu.NONE, CONTEXT_MENU_ID_EDIT,CONTEXT_MENU_ID_EDIT, HistoryFragment.this.getResources().getString(R.string.string_menu_edit));
                MenuItem menuItemDelete=contextMenu.add(Menu.NONE, CONTEXT_MENU_ID_DELETE,CONTEXT_MENU_ID_DELETE, HistoryFragment.this.getResources().getString(R.string.string_menu_delete));

                menuItemEdit.setOnMenuItemClickListener(this);
                menuItemDelete.setOnMenuItemClickListener(this);
            }

            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                int position=getAdapterPosition();
                Intent intent;
                switch(menuItem.getItemId())
                {
                    case CONTEXT_MENU_ID_EDIT:
                        intent = new Intent(HistoryFragment.this.getContext(), InputActivity.class);
                        intent.putExtra("position",position);
                        intent.putExtra("pictureId",accountTypeHistory.get(position).getPictureId());
                        intent.putExtra("type",accountTypeHistory.get(position).getType());
                        intent.putExtra("price",accountTypeHistory.get(position).getPrice());
                        intent.putExtra("payOrIncome",accountTypeHistory.get(position).getPayOrIncome());
                        intent.putExtra("payType",accountTypeHistory.get(position).getPayType());
                        intent.putExtra("date",accountTypeHistory.get(position).getDate());
                        launcherEdit.launch(intent);
                        break;
                    case CONTEXT_MENU_ID_DELETE:
                        AlertDialog.Builder alertDB = new AlertDialog.Builder(HistoryFragment.this.getContext());
                        alertDB.setPositiveButton(HistoryFragment.this.getContext().getResources().getString(R.string.string_confirmation), (dialogInterface, i) -> {
                            accountTypeHistory.remove(position);
                            dataBankHistory.saveData();
                            updateStatistics();
                            HistoryFragment.MyRecyclerViewAdapterHistory.this.notifyItemRemoved(position);
                        });
                        alertDB.setNegativeButton(HistoryFragment.this.getContext().getResources().getString(R.string.string_cancel), (dialogInterface, i) -> {

                        });
                        alertDB.setMessage(HistoryFragment.this.getContext().getResources().getString(R.string.string_confirm_delete));
                        alertDB.setTitle(HistoryFragment.this.getContext().getResources().getString(R.string.string_hint)).show();
                        break;
                }
                return false;
            }
        }
    }
    
}